from django import forms
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.db.models import Q
from django.conf import settings

from app01 import models
from app01.utils.script.bootstrap import BootStrapForm
from app01.utils.script.pager import Paginator
from app01.utils.script.response import BaseResponse

def policy_list(request):
    role = request.session.get(settings.SESSION_KEY)["role"]
    keyword = request.GET.get('keyword', '')
    con = Q()
    if keyword:
        con.connector = "OR"
        con.children.append(Q(count__icontains=keyword))
        con.children.append(Q(price__icontains=keyword))

    queryset = models.PricePolicy.objects.filter(con).all().order_by('count')
    obj = Paginator(request,queryset)
    page_string = obj.html()
    context={
        "role": role,
        "queryset": queryset[obj.start:obj.end],
        "page_string": page_string,
        "keyword": keyword
    }
    return render(request,"policy_list.html", context)

class PolicyModelForms(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.PricePolicy
        fields = ['count', 'price']
def policy_add(request):
    if request.method == 'GET':
        form = PolicyModelForms()
        return render(request,"form2.html",{"form": form})
    form =PolicyModelForms(data=request.POST)
    if not form.is_valid():
        return render(request,"form2.html",{"form":form})
    form.save()
    return redirect("/policy/list/")

def policy_edit(request, pk):

    policy_obj = models.PricePolicy.objects.filter(pk=pk).first()
    if request.method == "GET":
        form = PolicyModelForms(instance=policy_obj)
        return render(request,"form2.html",{"form":form})
    form = PolicyModelForms(data=request.POST, instance=policy_obj)
    if not form.is_valid():
        return render(request,"form2.html",{"form":form})
    form.save()
    return redirect("/policy/list/")


def policy_delete(request):
    cid = request.GET.get("cid",0)
    print(cid)
    res = BaseResponse()
    if not cid:
        res.detail = "请选择要删除的选项"
        return JsonResponse(res.dict)
    exists = models.PricePolicy.objects.filter(id=cid).exists()
    if not exists:
        res.detail = "该选项不存在"
        return JsonResponse(res.dict)
    models.PricePolicy.objects.filter(id=cid).delete()
    res.status=True
    return JsonResponse(res.dict)

